package com.gitee.wsl.security.encrypt.sample

import com.gitee.wsl.security.encrypt.Encrypt
import com.gitee.wsl.security.encrypt.StringToStringEncrypt


/** @link http://www.hiencode.com/tapcode.html */
object TapCode :StringToStringEncrypt{
    val table: String = TABLE_A_Z_WO_K
    val encodeMap: String = DEFAULT_POLYBIUS_ENCODE_MAP


    override fun encrypt(src: String): String =
        src.tapCode(table,encodeMap)

    override fun decrypt(src: String): String =
        src.tapCodeDecrypt(table,encodeMap)

}

val Encrypt.Companion.tapCode get() = TapCode



internal fun String.tapCode(
    table: String = TABLE_A_Z_WO_K,
    encodeMap: String = DEFAULT_POLYBIUS_ENCODE_MAP,
) = polybius(table, encodeMap, "K" to "C")

internal fun String.tapCodeDecrypt(
    table: String = TABLE_A_Z_WO_K,
    encodeMap: String = DEFAULT_POLYBIUS_ENCODE_MAP,
) = propTapCode().polybiusDecrypt(table, encodeMap)

private fun String.propTapCode() =
    if (contains("[.•]".toRegex())) {
        split("\\s{2,}".toRegex()).joinToString("") {
            val split = it.split("\\s+".toRegex())
            "${split[0].length}${split[1].length}"
        }
    } else {
        this
    }